package util

import (
	"encoding/json"
	"log"
	"net/http"
)

type H struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

func RespOk(writer http.ResponseWriter,  data interface{}, msg string)  {
	Resp(writer, 0, data, msg)
}

func RespFail(writer http.ResponseWriter, msg string)  {
	Resp(writer, -1,  nil, msg)
}

func Resp(writer http.ResponseWriter, code int,
	data interface{}, msg string)  {
	writer.Header().Set("Content-Type", "application/json")
	writer.WriteHeader(http.StatusOK)
	//定义一个结构体，把结构体转化为json字符串
	h := H{
		Code: code,
		Data: data,
		Msg: msg,
	}
	str, err := json.Marshal(h)
	if err != nil {
		log.Printf(err.Error())
	}
	//返回失败的json
	writer.Write([]byte(str))
}
